package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.BaseException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;
    //新增分类
    @Override
    public void save(CategoryDTO categoryDTO){
        //补全成普通实体类
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);

        category.setStatus(StatusConstant.ENABLE);


        categoryMapper.insert(category);

    }

    //分页查询
    @Override
    public PageResult pageList(CategoryPageQueryDTO categoryPageQueryDTO){
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        Page<Category> pageResult = (Page<Category>) categoryMapper
                .selectByNameAndType(categoryPageQueryDTO.getName()
                        ,categoryPageQueryDTO.getType());

        return new PageResult(pageResult.getTotal(),pageResult.getResult());
    }

    //修改分类状态
    @Override
    public void changeStatus(Integer status , Long id){
        //本质是修改分类信息，为了减少Mapper接口中的方法，先创建一个实体对象
        Category category = Category.builder()
                .id(id)
                .status(status)
                .build();
        categoryMapper.update(category);
    }


    //编辑分类信息
    @Override
    public void update(CategoryDTO categoryDTO){
        Category  category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        categoryMapper.update(category);
    }


    //根据类型查询分类
    @Override
    public List<Category> selectByType(Integer type){
        return categoryMapper.selectByNameAndType(null,type);
    }

    //根据ID删除分类
    @Override
    public void deleteById(Long id){

        Integer countSetmeal = setmealMapper.countByCategoryId(id);
        if(countSetmeal > 0){
            throw new BaseException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        Integer countDish = dishMapper.countByCategoryId(id);
        if(countDish > 0){
            throw new BaseException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        categoryMapper.deleteById(id);
    }
}
